layui.use(['laypage', 'layer', 'table', 'form', 'element', 'upload'], function() {
    var laypage = layui.laypage;//分页
    var layer = layui.layer; //弹层
    var table = layui.table; //表格
    var $ = layui.jquery;
    var form = layui.form;
    var element = layui.element; //元素操作
    var upload = layui.upload;


    var f_all = document.getElementById("pdf_manage");
    var f_all_h = f_all.offsetHeight - 146;
    var f_all_ht = f_all.offsetHeight - 36;

    var g_all = document.getElementById("pm_left_table");
    var g_all_h = g_all.offsetHeight - 50;

    var img_upload = upload.render({
        elem: '#pdfload'
        // ,data:{"dir_file":tree_dir_file}
        ,url: '/pdf-upload/'
        ,accept: 'file' //普通文件
        ,size: 10000
        ,done: function(res){
            if (res["status"] === 0){
                layer.msg("上传成功");
                p_file_list = res["p_file_list"];
                p_file_sel = res["p_file_sel"];
                filetable.reload({
                    data:res["p_file_list"]
                })
            }else if (res["status"] === 2){
                layer.msg("请上传PDF文件")
            }else if (res["status"] === 3) {
                layer.msg("PDF文件名称重复")
            }else{
                layer.msg("程序异常")
            }
        }
    });



    var table_format_file = [[
         {field: 'id', align: 'center', title: 'ID', width: "20%"}
         , {field: 'pdf_name', align: 'center', title: '文件名称', width: "60%"}
         , {fixed: 'right',width: "30%", align: 'center',  title: '操作', toolbar: '#filebutton'}
    ]];

    $('.layui-table-file').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtablef(etaleid,tableid,p_file_list,table_format_file,f_all_h);
        filetool(toolid,tableid);
    });

    var filetable;
    function createtablef(etaleid,tableid,datas,table_format,table_height) {
        filetable = table.render({
            elem: etaleid,
            id: tableid,
            height: table_height,
            limit: 10,
            page:true,
            data: datas,
            cols: table_format
        });
    }

    function filetool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            if (layEvent === "del_file"){
                console.log(data["id"]);
                $.ajax({
                    url: "/pdf-file-ops/",
                    dataType: 'json',
                    type: 'POST',
                    data:{"fid":data["id"]},
                    success: function (d_return_data) {
                        console.log(d_return_data)
                    }
                    
                })
            }
        })
    }

    var con_div = '<div class="pm-pdf-post"><form id="fileadd_pdf" name="fileadd_pdf" class="layui-form"><div class="layui-form-item"><label class="layui-form-label">匿名用户数</label><div class="layui-input-block"><input type="text" name="u_sum" autocomplete="off" required lay-verify="required" placeholder="请输入" class="layui-input"></div></div><div class="layui-form-item"><label class="layui-form-label">通用密码</label><div class="layui-input-block"><input type="text" name="u_password" autocomplete="off" required lay-verify="required" placeholder="请输入" class="layui-input"></div></div><div class="layui-form-item"><label class="layui-form-label">可阅读文档</label><div class="layui-input-block"><input id="p_list" type="text" name="p_list" autocomplete="off" required lay-verify="required" placeholder="请选择" class="layui-input"></div></div><div class="layui-form-item"><label class="layui-form-label">PDF选择</label><div class="layui-input-block"><select lay-filter="pdf_sel"><option value=""></option>';
    for (var i=0; i< p_file_sel.length; i++){
        console.log(p_file_sel[i]);
        con_div = con_div + '<option value="' + i + '" >' + p_file_sel[i] + '</option>'
    }
    var end_div = '</select></div></div><div class="layui-form-item"><button id="pdfsubmit" type="button" class="layui-btn layui-hide" lay-submit lay-filter="pdfsubmit">提交</button></div></form></div>';
    con_div = con_div + end_div;
    var open_index;
    $("#pdfgroup").on('click', function () {
       layer.open({
           type: 1,
           title: "创建用户组",
           closeBtn: false,
           area:  ['400px', '353px'],
           id: 'lay_group',
           btn: ['创建', '取消'],
           content:con_div,
           yes: function(index, layero){},
           success: function (layero,index) {
               form.render('select');
                var btn = layero.find('.layui-layer-btn');
                var btnn = layero.find('.layui-layer-btn0');
                btn.css('text-align', 'center');
                btnn.on('click', function () {
                    open_index  = index;
                    $("#pdfsubmit").trigger('click')
                })
            }
       })
    });


    form.on("submit(pdfsubmit)", function (pdata) {
        var r_data = pdata.field;
        layer.close(open_index);
        pdf_list_txt = "";
        var r_return_data = {"data":JSON.stringify(r_data), "type":0};
        ajaxgroup(r_return_data)
        // $.ajax({
        //     url: "/pdf-group-ops/",
        //     dataType: 'json',
        //     type: 'POST',
        //     data:r_return_data,
        //     success: function (d_return_data) {
        //         console.log(d_return_data)
        //     }
        // })
    });

    var pdf_list_txt = "";
    var c = [];
    form.on('select(pdf_sel)', function(data){
        var sel_num = data.value;
        if (pdf_list_txt === ""){
            pdf_list_txt = p_file_sel[sel_num]
            // pdf_list_txt = sel_num
        }else{
            pdf_list_txt += ','+p_file_sel[sel_num]
            // pdf_list_txt += ','+sel_num
        }

        console.log(pdf_list_txt);
        $("#p_list").val(pdf_list_txt)
    });


    //group 表
    console.log(1231231);
    var table_format_group = [[
         {field: 'id', align: 'center', title: 'ID', width: "20%"}
         , {field: 'u_sum', align: 'center', title: '用户数量', width: "15%"}
         , {field: 'u_list', align: 'center', title: 'PDF文件', width: "30%"}
         , {field: 'createTime', align: 'center', title: '创建时间', width: "25%"}
         , {fixed: 'right',width: "38%", align: 'center',  title: '操作', toolbar: '#groupbutton'}
    ]];

    $('.layui-table-manage').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtableg(etaleid,tableid,g_group_list,table_format_group,g_all_h);
        grouptool(toolid,tableid);
    });

    var grouptable;
    function createtableg(etaleid,tableid,datas,table_format,table_height) {
        grouptable = table.render({
            elem: etaleid,
            id: tableid,
            height: table_height,
            limit: 10,
            page:true,
            data: datas,
            cols: table_format
        });
    }

    function grouptool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            if (layEvent === "check_group"){
                var msg_to="<div style='width:300px;word-wrap:break-word;'>" + "用户名：" + data["user"] + '</br>' +"密码：" + data["u_password"] + "</div>";
                layer.msg(msg_to, {
                    time: 200000, //20s后自动关闭
                    btn: ['关闭'],
                    success: function (layero,index) {
                        var btn = layero.find('.layui-layer-btn');
                        btn.css('text-align', 'center');
                    }
                });
            }else if (layEvent === "mod_group") {
                var pdf_div = '<div style="width:90%;padding-top: 5%;"><form id="pdf_add" name="pdf_add" class="layui-form"><div id="pdf_list" class="layui-form-item"><label class="layui-form-label">可阅读文档</label><div class="layui-input-block"><input id="p_list" type="text" name="p_list" autocomplete="off" required lay-verify="required" placeholder="请选择" class="layui-input" disabled></div></div><div class="layui-form-item"><label class="layui-form-label">PDF选择</label><div class="layui-input-block"><select lay-filter="pdf_sel"><option value=""></option>';
                for (var i=0; i< p_file_sel.length; i++){
                    pdf_div = pdf_div + '<option value="' + i + '" >' + p_file_sel[i] + '</option>'
                }
                var pdf_end_div = '</select></div></div><div class="layui-form-item"><button id="pdfsubmit" type="button" class="layui-btn layui-hide" lay-submit lay-filter="pdfsubmit">提交</button></div></form></div>';
                pdf_div = pdf_div + pdf_end_div;
                layer.open({
                   type: 1,
                   title: "文档权限修改",
                   closeBtn: false,
                   area:  ['400px', '253px'],
                   id: 'lay_group_pdf',
                   btn: ['确定', '取消'],
                   content:pdf_div,
                   success: function (layero,index) {
                       form.render('select');
                       var p_new_list = eval(data["u_list"]);
                       pdf_list_txt = p_new_list.join(',');
                       $("#p_list").val(pdf_list_txt);
                        var btn = layero.find('.layui-layer-btn');
                        var btnn = layero.find('.layui-layer-btn0');
                        btn.css('text-align', 'center');
                        btnn.on('click', function () {
                            var r_p_data = {"id":data["id"],"p_list":$("#p_list").val()};
                            var r_p_return = {"data":JSON.stringify(r_p_data), "type":3};
                            ajaxgroup(r_p_return);
                            pdf_list_txt=""
                        })
                    }
               })

            }else if (layEvent === "add_group") {
                var r_add_data = {"g_id": data["id"],"u_sum": 0, "u_password": data["u_password"],"old_num":data["u_sum"], "p_list":data["u_list"]};
                var add_num;
                var add_context =  '<div style="width:90%;height100%:"><form id="useradd_pdf" name="useradd_pdf" class="layui-form"><div class="layui-form-item"><label class="layui-form-label">新增用户数</label><div class="layui-input-block"><input id="add_num" type="text" name="u_sum" autocomplete="off" required lay-verify="required" placeholder="请输入" class="layui-input"></div></div></form></div>';
                layer.open({
                   type: 1,
                   title: "添加用户",
                   closeBtn: false,
                   area:  ['350px', '130px'],
                   id: 'lay_add',
                   btn: ['添加', '取消'],
                   content:add_context,
                   success: function (layero,index) {
                        var btn = layero.find('.layui-layer-btn');
                        var btnn = layero.find('.layui-layer-btn0');
                        btn.css('text-align', 'center');
                        btnn.on('click', function () {
                            add_num = parseInt($("#add_num").val());
                            if (isNaN(add_num) || add_num <= 0){
                                layer.msg("输入数据不正确！")
                            }else{
                                r_add_data["u_sum"] = add_num;
                                var r_data = {"data":JSON.stringify(r_add_data), "type":2};
                                ajaxgroup(r_data)
                                // $.ajax({
                                //     url: "/pdf-group-ops/",
                                //     dataType: 'json',
                                //     type: 'POST',
                                //     data:r_data,
                                //     success: function (d_return_data) {
                                //         console.log(d_return_data)
                                //     }
                                // })
                            }
                        })
                    }
                });
            }else if (layEvent === "del_group") {
                var r_d_data = {"id":data["id"],"type":1};
                ajaxgroup(r_d_data)
            }
        })
    }

    function ajaxgroup(data) {
        $.ajax({
            url: "/pdf-group-ops/",
            dataType: 'json',
            type: 'POST',
            data:data,
            success: function (g_return_data) {
                if (g_return_data["status"] === 0){
                    g_group_list = g_return_data["g_group_list"];
                    grouptable.reload({
                        data:g_group_list
                    })
                }
            }
        })
    }

    $('.demoTable .layui-btn').on('click',
        function() {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        }
    );
});